from flask import Blueprint, render_template, request, redirect, url_for
from database import user_student
from student_manager import StudentManager

stu = Blueprint("stu", __name__, url_prefix="/stu")
student_manager = StudentManager()


@stu.route("/")
def index():
    che_name = request.args.get("che")  # 获取查询的名字
    if che_name:  # 如果有查询，则判断是否存在
        che_student = student_manager.check_student(che_name)
        if not che_student:
            return render_template("index.html", user=user_student, error_message="查找不存在")
        else:
            return render_template("index.html", user=che_student)

    sid = request.args.get("del")
    if sid:
        student_manager.delete_student(int(sid))

    return render_template("index.html", user=user_student)


@stu.route("/add", methods=["GET", "POST"])
def add():
    if request.method == "POST":
        sid = request.form["sid"]
        name = request.form["name"]
        age = request.form["age"]
        gender = request.form["gender"]

        error_message = student_manager.valid(sid, name, age, gender, True)  # 检查是否符合
        if not error_message:  # 符合的信息添加到数据库中
            student_manager.add_student(sid, name, age, gender)
            return redirect(url_for("stu.index"))

        return render_template("add.html", error_message=error_message)  # 不符合的信息返回报错

    return render_template("add.html")


@stu.route("/correct/<int:sid>", methods=["GET", "POST"])
def correct(sid):
    if request.method == "GET":  # GET请求，打印原本的信息
        for stu in user_student:
            if sid == stu.get("sid"):
                return render_template("cha.html", user=stu)
    else:  # 获取新的数据
        name = request.form["name"]
        age = request.form["age"]
        gender = request.form["gender"]

        new_stu = []  # 获取原本的数据，以至于错误时，返回原本的数据
        for stu in user_student:
            if sid == stu.get("sid"):
                new_stu = stu

        error_message = student_manager.valid(sid, name, age, gender, False)  # 检查是否符合
        if not error_message:
            student_manager.correct_student(sid, name, age, gender)
            return redirect(url_for("stu.index"))

        return render_template("cha.html", error_message=error_message, user=new_stu)